package com.monkeygroup.mygoplus.view.home.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.graphics.drawable.Drawable;

import com.monkeygroup.mygoplus.R;
import com.monkeygroup.mygoplus.base.BaseActivity;
import com.monkeygroup.mygoplus.common.DefinedView.MyAlertDialog;
import com.monkeygroup.mygoplus.common.utils.LocalInfo;
import com.monkeygroup.mygoplus.common.utils.StringUtil;
import com.monkeygroup.mygoplus.thing.vo.ZoneVO;
import com.monkeygroup.mygoplus.view.home.activity.rent.PublishedRentActivity;
import com.monkeygroup.mygoplus.view.home.activity.rent.PublishedRentLandAcitivity;
import com.monkeygroup.mygoplus.view.home.activity.rent.PublishedRentOfficeActivity;
import com.monkeygroup.mygoplus.view.home.activity.rent.PublishedRentShopAcitivity;
import com.monkeygroup.mygoplus.view.home.activity.sell.PublishedActivity;
import com.monkeygroup.mygoplus.view.home.activity.sell.PublishedLandActivity;
import com.monkeygroup.mygoplus.view.home.activity.sell.PublishedShopActivity;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import android.widget.ListView;
import android.widget.EditText;



import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.text.SpannableString;
import android.graphics.Color;
import android.text.style.ForegroundColorSpan;
import android.text.Spanned;


/**
 * Created by cumt on 2017/5/27.
 */

public class PublishedChooseAddrActivity  extends BaseActivity implements View.OnClickListener{


    public static void gotoActivity(Activity activity,String type) {
        Intent intent = new Intent(activity,
                PublishedChooseAddrActivity.class);
        intent.putExtra("type", type);

        activity.startActivityForResult(intent,11);

    }


    private ImageView imgBack;
    private TextView txtTitle;

    private String searchKey="";
    private EditText txt_search_content;

    private ListView publishAddrList;

    private LeftAdapter adapter;
    private List<ZoneVO> leftListItems;

    private String level="1";

    private String type;

    @Override
    public void onClick(View v) {

    }

    @Override
    public void setContentView() {
        setContentView(R.layout.published_choose_addr);

    }

    @Override
    public void initView() {

        imgBack = (ImageView) findViewById(R.id.img_back);
        txtTitle = (TextView) findViewById(R.id.txt_title);
        txtTitle.setText("請選擇縣市");

        txt_search_content= (EditText) findViewById(R.id.txt_search_content);

        leftListItems  =new ArrayList<ZoneVO>();
        publishAddrList= (ListView) findViewById(R.id.publish_addr_list);

        Intent intent = this.getIntent();
        Bundle bundle =  intent.getExtras();
        type = bundle.getString("type");

        initData();
    }

    @Override
    public void setListener() {
//        txt_search_content.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//
//                Drawable drawable = getResources().getDrawable(R.mipmap.icon_search_nor2x);
//                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
//                txt_search_content.setCompoundDrawables(null, null, drawable, null);
//
//            }
//        });

        txt_search_content.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                //焦點
                if (hasFocus) {
                    Drawable drawable = getResources().getDrawable(R.mipmap.btn_est_redcancel_nor2x);
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                    txt_search_content.setCompoundDrawables(null, null, drawable, null);
                }

            }
        });
        txt_search_content.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // et.getCompoundDrawables()得到一个长度为4的数组，分别表示左右上下四张图片
                Drawable drawable = txt_search_content.getCompoundDrawables()[2];
                //如果右边没有图片，不再处理
                if (drawable == null)
                    return false;
                //如果不是按下事件，不再处理
                if (event.getAction() != MotionEvent.ACTION_UP)
                    return false;
                if (event.getX() > txt_search_content.getWidth()
                        - txt_search_content.getPaddingRight()
                        - drawable.getIntrinsicWidth()){
                    txt_search_content.setText("");
                }
                return false;
            }
        });

        TextWatcher search=new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
              //  if(!StringUtil.isBlank(String.valueOf(txt_search_content))){
                    searchKey=String.valueOf(txt_search_content.getText());
                    leftListItems.clear();
                    InputStream cityinputStream = getResources().openRawResource(R.raw.city);
                    List<ZoneVO> cityVOs = getString("15801",cityinputStream,String.valueOf(txt_search_content.getText()));
                    leftListItems.addAll(cityVOs);
                    adapter.notifyDataSetChanged();
             //   }


            }

            @Override
            public void afterTextChanged(Editable s) {


            }
        };
        txt_search_content.addTextChangedListener(search);

    }

    @Override
    public void doEvent() {

    }

    private void initData(){

         adapter = new LeftAdapter(PublishedChooseAddrActivity.this);
        publishAddrList.setAdapter(adapter);

        InputStream cityinputStream = getResources().openRawResource(R.raw.city);
        List<ZoneVO> cityVOs = getString("15801",cityinputStream,"");



        leftListItems.addAll(cityVOs);

    }

    /**
     * 读取城市地区
     * @param inputStream
     * @return
     */
    public static List<ZoneVO> getString(String pid,InputStream inputStream,String searchKey) {
        InputStreamReader inputStreamReader = null;
        try {
            inputStreamReader = new InputStreamReader(inputStream, "gbk");
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        BufferedReader reader = new BufferedReader(inputStreamReader);

        List<ZoneVO> zoneList = new ArrayList<ZoneVO>();
        String line;
        try {
            while ((line = reader.readLine()) != null) {

                String[] zone = line.split(",");

                if(pid.equals(zone[2])){

                    ZoneVO vo = new ZoneVO();
                    vo.setId(zone[0]);
                    vo.setName(zone[1]);
                    vo.setPid(zone[2]);
                    if(zone.length>3){
                        vo.setLat(zone[3]);
                        vo.setLng(zone[4]);
                    }
                    if(!StringUtil.isBlank(searchKey)){
                        if(vo.getName().contains(searchKey)){
                            zoneList.add(vo);
                        }
                    }
                    else{
                        zoneList.add(vo);
                    }

                }


            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return zoneList;
    }

    public class LeftAdapter extends BaseAdapter {


        private LayoutInflater mInflater;
        final Intent intent=new Intent();

        private List<ZoneVO> streetVOs,areaVOs=null ;


        public LeftAdapter(Context context) {
            this.mInflater = LayoutInflater.from(context);
        }

        @Override
        public int getCount() {
            return leftListItems.size();
        }

        @Override
        public Object getItem(int position) {
            return leftListItems.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View myconvertView, ViewGroup parent) {

            View leftconvertView = mInflater.inflate(R.layout.published_second_item, null);
            final ZoneVO obj = leftListItems.get(position);
            final TextView txtName = (TextView) leftconvertView
                    .findViewById(R.id.txt_publish_content);

            if(!StringUtil.isBlank(searchKey)){
                SpannableString s = new SpannableString(obj.getName());

                Pattern p = Pattern.compile(searchKey);
                Matcher m = p.matcher(s);

                while (m.find()) {
                    int start = m.start();
                    int end = m.end();
                    s.setSpan(new ForegroundColorSpan(Color.RED), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                }
                txtName.setText(s);
            }
            else{
                txtName.setText(obj.getName());
            }

            leftconvertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                Log.e("levellevel==",""+level);
                    intent.putExtra("type", type);
                if("1".equals(level)&&areaVOs==null){
                    intent.putExtra("property_city", obj.getName());
                    intent.putExtra("property_city_id", obj.getId());
                    InputStream areainputStream = getResources().openRawResource(R.raw.area);
                     areaVOs = getString(obj.getId(),areainputStream,"");
                    leftListItems.clear();
                    leftListItems.addAll(areaVOs);
                    txtTitle.setText(obj.getName());


                    level="2";
                }
                //區
                else if("2".equals(level)&areaVOs!=null&&streetVOs==null){
                    intent.putExtra("property_area", obj.getName());
                    intent.putExtra("property_area_id", obj.getId());
                    txtTitle.setText(obj.getName());
                    InputStream areainputStream = getResources().openRawResource(R.raw.street);
                    streetVOs = getString(obj.getId(),areainputStream,"");

                    leftListItems.clear();
                    leftListItems.addAll(streetVOs);
                    if("3".equals(type)||"4".equals(type)){
                        PublishedChooseAddrActivity.this.setResult(RESULT_OK,intent);
                        finish();
                    }
                    level="3";
                }
                else if("3".equals(level)&&streetVOs!=null){
                    intent.putExtra("property_street", obj.getName());
                    intent.putExtra("property_street_id", obj.getId());
                    txtTitle.setText(obj.getName());

                    PublishedChooseAddrActivity.this.setResult(RESULT_OK,intent);
                    finish();
                }
                    adapter.notifyDataSetChanged();

                }
            });

            return leftconvertView;
        }

    }

    }
